/**
 * Created by apple on 16/6/27.
 */
angular.module('starter.userController', ['starter.userService'])
  //引导中间页
  .controller("GuideTempCtrl", function ($update,$scope, $state, $dfCache, $ionicPopup, $timeout, $region, $design, $lookup, $supplier, $cordovaSplashscreen, $ionicHistory, $interval) {
    $scope.isSuccess = false;
    $scope.isShow = false;

    if (window.plugins && window.plugins.jPushPlugin){
      window.plugins.jPushPlugin.setAlias("");
    }

    //变量
    var region = "";
    var item = "";
    var array = "";
    var supplier = "";

    //获取本地缓存状态
    function getLocalCache() {
      //获取本地缓存
      region = $region.get();
      item = $design.getWithProperty({});
      array = $lookup.get();
      supplier = $supplier.getWithProperty({});

      var flag = false;

      if (region.data.length != 0 && item.length != 0 && array.length != 0 && supplier.length != 0) {
        flag = true;
      }

      return flag;
    }

    $scope.$on('$ionicView.enter', function () {
      var progress = document.getElementById("progress");

      $timeout(function () {
        request();
      }, 500);

      function request() {
        //判断获取本地缓存是否成功
        if (getLocalCache()) {
          $scope.isShow = false;
          $scope.isSuccess = true;
          //$state.go("login", {}, {animation: "no-animation"});
          $update.update();
        } else {
          $scope.isShow = true;
          $scope.isSuccess = false;

          if (region.data.length == 0) {
            $region.dfHttpGet();
          }

          if (item.length == 0) {
            $design.dfHttpGet();
          }

          if (array.length == 0) {
            $lookup.syncLookup();
          }

          if (supplier.length == 0) {
            $supplier.dfHttpGet();
          }

          var i = 0;
          var time = $interval(function () {
            i++;
            if (getLocalCache()) {
              $scope.isShow = false;
              $scope.isSuccess = true;
              $interval.cancel(time);
              //$state.go("login", {}, {animation: "no-animation"});
              $update.update();
            }

            if (i == 30) {
              $ionicPopup.confirm({
                title: "失败",
                template: "请求失败，请重试",
                buttons: [
                  {
                    text: "<b>重试</b>",
                    type: "button-positive",
                    onTap: function () {
                      progress.className = "progress";
                      $timeout(function () {
                        progress.className = "progress animation-error";
                        request();
                      }, 500);
                    }
                  }
                ]
              });
            }
          }, 500, 30);
        }
      }
    });
  })

  .controller('LoginCtrl', function ($ionicHistory, $cordovaKeyboard,$cordovaDialogs,$log, $lookup, $scope, $user, $ionicPopup, $state, $loading, $dfImagePicker, $region, $timeout, $cordovaSplashscreen) {
    //初始化对象
    $scope.data = {};



    $timeout(function(){

      if( typeof ($user.getCurrentUserSync().autoLogin) == 'undefined'){
        $scope.data.autoLogin = true;
      }else{
        $scope.data.autoLogin = $user.getCurrentUserSync().autoLogin;
      }
      $user.getCurrentUser().executeSuccess(function (user) {
        // 判断是否为自动登录
        // alert(user.autoLogin);
        if (user.autoLogin) {
          login(user.userPhone, user.password);
        }else{
          $scope.data.username = user.userPhone;
          $scope.data.password = user.password;
        }
      });

    },300);

    // 回退到登录页面
    $scope.$on("$ionicView.beforeEnter", function () {
      $ionicHistory.clearHistory();
      $ionicHistory.clearCache();
    });


    // 封装登陆方法
    function login(username, password) {

      // 判断
      if (!(/^1[34578]\d{9}$/.test(username))) {
        $cordovaDialogs.alert('请输入正确的手机号','提示','确定');
      } else if (password.length < 6 || password === 'undefined' ) {
        $cordovaDialogs.alert('密码不能少于6位','提示','确定');
      } else {
        $loading.show("登录中");
        //请求服务
        $user.loginUser(username, password)
          .success(function (data) {
            if (data.code == 'SUCCESS') {
              //保存密码
              data.data.password = password;
              data.data.autoLogin = $scope.data.autoLogin;
              data.data.currentLogin = true ;
              $user.saveUser(data.data);
              $state.go('tab.tasks');
              $loading.hide();

              window.plugins.jPushPlugin.setAlias(data.data.userPhone)
            } else {
              $loading.showError(data.msg);
            }
          }).error(function (data) {
          //  $state.go('delivery');
            $loading.showError("登录失败,请重试");
        });
      }
    }

    var onTagsWithAlias = function(event) {
      try {
        console.log("onTagsWithAlias");
        if(event && event.resultCode == 0) {
          return ;
        } else {
          var result = "result code:" + event.resultCode + " ";
          result += "tags:" + event.tags + " ";
          result += "alias:" + event.alias + " ";
          if (event && event.alias != '') {
            window.plugins.jPushPlugin.setAlias(event.alias);
          }
        }

      } catch(exception) {
        console.log(exception);
      }
    }
    document.addEventListener("jpush.setTagsWithAlias", onTagsWithAlias, false);

    //登录
    $scope.login = function () {
      login($scope.data.username, $scope.data.password);
    }

    $scope.showZBar = function () {
      cloudSky.zBar.scan({
        text_title: "OPTIONAL Title Text - default = 'Scan QR Code'", // Android only
        text_instructions: "OPTIONAL Instruction Text - default = 'Please point your camera at the QR code.'", // Android only
        camera: "back", // defaults to "back"
        flash: "off", // defaults to "auto". See Quirks
        drawSight: true //defaults to true, create a red sight/line in the center of the scanner view.
      },function(data){

      },function(error){

      });
    }

    // 忘记密码
    $scope.doForget = function () {
      $state.go("reset");
    }
  })

  // 重置密码控制
  .controller("ResetCtrl", function ($scope, $user, $loading, $state, $timeout) {
    // 定义变量
    $scope.vm = {}; //空对象
    $scope.vm.flag = false; //密码状态标记

    // 获取验证码
    $scope.getSecurityCode = function () {
      // 变量
      var userPhone = $scope.vm.userPhone; //手机号
      var businessType = -2; //类型：重置

      // 判断手机号是否为空
      if (userPhone == "" || userPhone == null) {
        $loading.showError("请输入手机号！");
      } else {
        $user.getSecurityCode(userPhone, businessType).success(function (data) {
          if (data.code == "SUCCESS") {
            $loading.showSuccess(data.msg);
          } else {
            // 错误结果
            var errorRes = "";

            if (data.code == "FAILURE") {
              errorRes = data.msg;
            } else {
              errorRes = "网络出了一点小问题,请稍后再试！";
            }

            // 输出错误结果
            $loading.showError(errorRes);
          }
        }).error(function () {
          $loading.showError("请求服务失败，请稍后再试");
        });
      }
    }

    // 重置密码
    $scope.reset = function () {
      var userPhone = $scope.vm.userPhone; // 手机号
      var securityCode = $scope.vm.securityCode; // 验证码
      var newPassword = $scope.vm.newPassword; // 新密码

      // 点击重置后的逻辑判断
      if (securityCode == null || securityCode == "") { // 判断验证码是否为空
        $loading.showError("请输入验证码!");
      } else if (newPassword == null || newPassword == "") { // 判断新密码是否为空
        $loading.showError("请输入密码");
      } else { //请求服务
        $user.resetPassword(userPhone, securityCode, newPassword).success(function (data) {
          if (data.code == "SUCCESS") {
            $loading.showSuccess(data.msg);

            // 重置成功后将字段清空
            $scope.vm = {};

            // 延长显示时间
            $timeout(function () {
              $state.go("login");
            }, 1000);
          } else {
            // 错误结果
            var errorRes = "";

            if (data.code == "FAILURE") {
              errorRes = data.msg
            } else {
              errorRes = "网络出了一点小问题,请稍后再试！";
            }

            // 输出错误结果
            $loading.showError(errorRes);
          }
        }).error(function () {
          $loading.showError("请求服务失败，请稍后再试")
        });
      }
    }

    // 更改密码状态
    $scope.passwordStatus = function () {
      $scope.vm.flag = !$scope.vm.flag;
    }
  })
